package com.zt.rongda.stock.service;

import java.text.SimpleDateFormat;
import java.util.List;

import com.zt.rongda.stock.inter.StockInventoryMapper;
import com.zt.rongda.stock.model.StockInventory;
import com.zt.system.model.BusinessException;
import com.zt.servlet.ReqBean;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.util.DateUtil;
import com.zt.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class StockInventoryService extends BaseService {

    @Autowired
    private StockInventoryMapper stockInventoryMapper;

    /**
    * 查询
    *
    * @param reqBean
    * @return
    */
    public JSONObject getTable(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("");
        sqlBuilder.appendSql("select * from STOCK_INVENTORY where 1=1 ");

        sqlBuilder.addWhereLike2("STOCK_NAME", reqBean.getInfo("stockName"));
        sqlBuilder.addWhereLike2("TYPE_NAME", reqBean.getInfo("typeName"));

        // 时间间隔
        String endDate = reqBean.getInfo("inventoryTimeEnd");
        if(endDate != null && endDate.length()>=10)
        {
            Date tmp_date =  DateUtil.parse(endDate);

            SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
            endDate = df.format(new Date(tmp_date.getTime() + 1 * 24 * 60 * 60 * 1000)); // 结束日期加一天
        }
        sqlBuilder.addTimeWhere("INVENTORY_TIME", reqBean.getInfo("inventoryTimeStart"), ">=");
        sqlBuilder.addTimeWhere("INVENTORY_TIME", endDate, "<");
        //

        return queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
    }

    /**
    * 通过id查询
    *
    * @param stockId
    * @return
    */
    public StockInventory getById(String stockId) {
        return stockInventoryMapper.selectByPrimaryKey(stockId);
    }

    /**
    * 新增
    *
    * @param stockInventory
    */
    public void add(StockInventory stockInventory) {
        stockInventory.setStockId(stringId());// 手动设置Id

        stockInventory.setMakeTime(new Date());
        stockInventory.setModifyTime(stockInventory.getMakeTime());
        stockInventoryMapper.insert(stockInventory);
    }

    /**
    * 修改
    *
    * @param stockInventory
    */
    public void update(StockInventory stockInventory) {
        String stockId = stockInventory.getStockId();
        if (StringUtil.isEmpty(stockId)) {
            throw new BusinessException("获取主键失败");
        }

        stockInventory.setModifyTime(new Date());
        stockInventoryMapper.updateByPrimaryKeySelective(stockInventory);
    }

    /**
    * 删除
    *
    * @param stockId
    */
    public void delete(String stockId) {
        if (StringUtil.isEmpty(stockId)) {
            throw new BusinessException("获取主键失败");
        }
        stockInventoryMapper.deleteByPrimaryKey(stockId);
    }

}